// 📊 S3策略：终极容错 + 多窗口融合策略
const _ = require("lodash");

/**
 * 评分策略核心：
 * 分数 = 热度 * 2 + 未开期数 * 1 - 连错惩罚 * 1.5
 * 最后从多个窗口评分加权平均，选出前 32 个号码
 *
 * @param {Array<{ time: string, number: string }>} temp
 * @returns {string[]} - 返回预测的 32 个号码
 */
function select32NumbersByS3(temp) {
  const allNumbers = Array.from({ length: 49 }, (_, i) =>
    (i + 1).toString().padStart(2, "0")
  );

  // ✅ 设定融合窗口组（防止单窗口偏差）
  const windowSizes = [20, 40, 60];
  const scoreMap = {};

  windowSizes.forEach((winSize) => {
    const subTemp = temp.slice(-winSize);
    const freqMap = {};
    const lastAppearMap = {};
    const wrongStreakMap = {};

    // 初始化 wrongStreakMap
    allNumbers.forEach((n) => (wrongStreakMap[n] = 0));

    // 统计连错次数 + 频率 + 最近出现期
    for (let i = subTemp.length - 1; i >= 0; i--) {
      const num = subTemp[i].number;

      allNumbers.forEach((n) => {
        if (n === num) {
          wrongStreakMap[n] = 0;
        } else {
          wrongStreakMap[n]++;
        }
      });

      freqMap[num] = (freqMap[num] || 0) + 1;
      lastAppearMap[num] = i;
    }

    // 评分：热度、未开期数、连错惩罚
    allNumbers.forEach((n) => {
      const freq = freqMap[n] || 0;
      const lastIndex = lastAppearMap[n];
      const gap = lastIndex !== undefined ? subTemp.length - 1 - lastIndex : subTemp.length;
      const wrong = wrongStreakMap[n] || 0;

      const score = freq * 2 + gap * 1 - wrong * 1.5;

      scoreMap[n] = (scoreMap[n] || 0) + score; // 融合得分（加权平均）
    });
  });

  // ✅ 最终选出得分最高的 32 个号码
  const result = Object.entries(scoreMap)
    .sort((a, b) => b[1] - a[1])
    .slice(0, 32)
    .map(([num]) => num);

  return result;
}

module.exports = select32NumbersByS3;
